package indi.zhifa.core.common.web.config.web;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;


@Slf4j
@Configuration
public class LocalDateTimeSerializerConfig {
    DateTimeFormatter localDateTimeDf;
    DateTimeFormatter localDateDf;
    DateTimeFormatter localTimeDf;

    @EventListener(ContextRefreshedEvent.class)
    protected void init(){
        localDateTimeDf = new DateTimeFormatterBuilder()
                .parseCaseInsensitive()
                .append(DateTimeFormatter.ISO_LOCAL_DATE)
                .appendLiteral(' ')
                .append(DateTimeFormatter.ISO_LOCAL_TIME)
                .toFormatter();
        localDateDf = new DateTimeFormatterBuilder()
                .parseCaseInsensitive()
                .append(DateTimeFormatter.ISO_LOCAL_DATE)
                .toFormatter();
        localTimeDf = new DateTimeFormatterBuilder()
                .parseCaseInsensitive()
                .append(DateTimeFormatter.ISO_LOCAL_TIME)
                .toFormatter();
    }
    @Bean
    public Converter<String, LocalDateTime> localDateTimeConvert() {
        return new Converter<String, LocalDateTime>() {
            @Override
            public LocalDateTime convert( String source) {
                if(!StringUtils.hasText(source)){
                    return null;
                }
                LocalDateTime time = LocalDateTime.parse(source, localDateTimeDf);
                return time;
            }
        };
    }

    @Bean
    public Converter<String, LocalDate> localDateConvert() {
        return new Converter<String, LocalDate>() {
            @Override
            public LocalDate convert( String source) {
                if(!StringUtils.hasText(source)){
                    return null;
                }
                LocalDate time = LocalDate.parse(source, localDateDf);
                return time;
            }
        };
    }

    @Bean
    public Converter<String, LocalTime> localTimeConvert() {
        return new Converter<String, LocalTime>() {
            @Override
            public LocalTime convert( String source) {
                if(!StringUtils.hasText(source)){
                    return null;
                }
                LocalTime time = LocalTime.parse(source, localTimeDf);
                return time;
            }
        };
    }
}
